import os
import xbmc
import xbmcgui
import xbmcaddon

# Script constants
g_addon				= xbmcaddon.Addon(id='script.partymode.autostart')

g_scriptId			= g_addon.getAddonInfo('id')
g_scriptName		= g_addon.getAddonInfo('name')
g_scriptAuthor		= g_addon.getAddonInfo('author')
g_scriptVersion		= g_addon.getAddonInfo('version')
g_scriptLanguage 	= g_addon.getLocalizedString
g_scriptPath		= g_addon.getAddonInfo('path')

g_preLogString 		= "[SCRIPT] '%s: version %s' " % ( g_scriptName, g_scriptVersion )

def Main():
	print g_preLogString + "initialized!"
	
	# Start partymode if script is called from autostart.py (with 'partymode' param) 
	if len(sys.argv) > 1:
		# The core of script ;)
		xbmc.executebuiltin("XBMC.PlayerControl(PartyMode)")
		
		visualisation = g_addon.getSetting( 'visualisation' )
		print g_preLogString + visualisation
		if visualisation == '0':
			xbmc.sleep(1000) 
			xbmc.executebuiltin("XBMC.ActivateWindow(home)")
			print g_preLogString + "go to home!"
		elif visualisation == '1':
			xbmc.sleep(1000) 
			xbmc.executebuiltin("XBMC.ActivateWindow(visualisation)")
			print g_preLogString + "go to visualisation mode!"
			
		# This apply setting also when autostart partymode...but see the effect on 2 restart...
		setAutoexec( g_addon.getSetting( 'autostart' ) == 'true' )
		
	else:
		g_addon.openSettings()
		autostart =  setAutoexec( g_addon.getSetting( 'autostart' ) == 'true' )
		if autostart:
			xbmcgui.Dialog().ok("Applied","Party Mode start on next restart...")
		else:
			xbmcgui.Dialog().ok("Applied","Party Mode DON'T start on next restart...")

# THANKS mmdb autor of MyMediaDB script for setAutoexec function source
# autoexecute addon on startup for older xbmc versions, remove this when xbmc.service goes live (afther dharma)
def setAutoexec( autostart ):
	# Auto exec info
	AUTOEXEC_PATH = xbmc.translatePath( 'special://home/userdata/autoexec.py' )
	AUTOEXEC_FOLDER_PATH = xbmc.translatePath( 'special://home/userdata/' )
	AUTOEXEC_SCRIPT = '\nimport time;time.sleep(5);xbmc.executebuiltin("XBMC.RunScript(special://home/addons/%s/default.py,partymode)")\n' % g_scriptId
	
	# See if the autoexec.py file exists
	if (os.path.exists(AUTOEXEC_PATH)):
		print g_preLogString + 'autoexec.py exist ...'
		
		# Var to check if we're in autoexec.py
		found = False
		autoexecfile = file( AUTOEXEC_PATH, 'r' )
		filecontents = autoexecfile.readlines()
		autoexecfile.close()
		
		# Check if we're in it
		for line in filecontents:
			if line.find( g_scriptId ) > 0:
				print g_preLogString + 'just present in autoexec.py'
				found = True
				return True

		# If the autoexec.py file is found and we're not in it,
		if (not found and autostart):
			print g_preLogString + 'adding ourselves to autoexec.py'
			autoexecfile = file( AUTOEXEC_PATH, 'w' )
			filecontents.append( AUTOEXEC_SCRIPT )
			autoexecfile.writelines( filecontents )            
			autoexecfile.close()
			return True
		
		# Found that we're in it and it's time to remove ourselves
		if (found and not autostart):
			print g_preLogString + 'removing ourselves from autoexec.py'
			autoexecfile = file( AUTOEXEC_PATH, 'w' )
			for line in filecontents:
				if not line.find( g_scriptId ) > 0:
					autoexecfile.write( line )
			autoexecfile.close()
			return False
			
	elif ( autostart ):
		print g_preLogString + 'autoexec.py doesn\'t exist'
		if (os.path.exists(AUTOEXEC_FOLDER_PATH)):
			print g_preLogString + 'creating autoexec.py with our autostart script'
			autoexecfile = file(AUTOEXEC_PATH, 'w')
			autoexecfile.write (AUTOEXEC_SCRIPT.strip())
			autoexecfile.close()
		else:
			print g_preLogString + 'scripts folder missing, creating autoexec.py in that new folder with our script'
			os.makedirs(AUTOEXEC_FOLDER_PATH)
			autoexecfile = file(AUTOEXEC_PATH, 'w')
			autoexecfile.write (AUTOEXEC_SCRIPT.strip())
			autoexecfile.close()
		return True
	return False

if ( __name__ == "__main__" ):
	print "## Script ##################################################"
	print "#       id: %-43s    #" % g_scriptId
	print "#     name: %-43s    #" % g_scriptName
	print "#   author: %-43s    #" % g_scriptAuthor
	print "#  version: %-43s    #" % g_scriptVersion
	print "############################################################"
	Main()